﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Lib.Paging;
using System.IO;
using SDT.Site.ViewModels;
using SDT.Site.Properties;
using System.Web.Security;

namespace SDT.Site.Controllers
{
    public class VideoController : Controller
    {
        //
        // GET: /Video/

        SDTDataContext db = new SDTDataContext();
        public ActionResult Index()
        {
            VideoIndexViewModels v = new VideoIndexViewModels();
            string order = UserState.getUserStateFromRequest("video.order", "order", "AddDate").ToString();
            string orderDir = UserState.getUserStateFromRequest("video.orderDir", "orderDir", "desc").ToString();
            v.VideoImagePath = Settings.Default.SiteRootPath + Settings.Default.VideoImageRootPath;
            v.VideoImageUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoImagePreviewUrlPrefix;

            v.VideoFilePath = Settings.Default.SiteRootPath + Settings.Default.VideoRootPath;
            v.VideoFileUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoPreviewUrlPrefix;

            v.Categories = db.VideoCategories.Where(vc => vc.ActiveYN == true).ToList();
            v.VideoNewest = db.Videos.Where(e => e.PubYN == true)
                                 .OrderBy(string.Format("{0} {1}", order, orderDir))
                                 .Take(5).ToList();

            return View(v);
        }

        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 05/08/2011
        /// </summary>
        public ActionResult Category(int id)
        {
            VideoListViewModel videoModel = new VideoListViewModel();

            string order = UserState.getUserStateFromRequest("videoCategory.order", "order", "AddDate").ToString();
            string orderDir = UserState.getUserStateFromRequest("videoCategory.orderDir", "orderDir", "desc").ToString();
            int pageNumber = Convert.ToInt32(UserState.getUserStateFromRequest("videoCategory.PageNumber", "page", 1));
            int pageSize = int.Parse(UserState.getUserStateFromRequest("videoCategory.pageSize", "PageSize", 20).ToString());
            
            // Added by Vietlv (16/009/2011) : Get category by companyID
            var companyID = Request["companyID"] != null && Request["companyID"].Length > 0 ? Convert.ToInt32(Request["companyID"]) : 0; 
            var listIdVideo = db.VideoCompanyMaps
                                .Where(e => companyID > 0 ? e.CompanyID == companyID : false)
                                .Select(e => e.VideoID)
                                .ToList();
            videoModel.VideoImageUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoRootUrl;
            videoModel.Category = db.VideoCategories.Where(vc => vc.ActiveYN == true && vc.ID == id).FirstOrDefault();
            if (companyID > 0) // Added by Vietlv
            {
                videoModel.Videos = db.Videos.Where(e => e.PubYN == true)
                                 .Where(e => listIdVideo != null && listIdVideo.Count > 0 ? listIdVideo.Contains(e.ID) : false)
                                 .OrderBy(string.Format("{0} {1}", order, orderDir))
                                 .ToPagedList(pageNumber - 1, pageSize);
            }
            else
            {
                videoModel.Videos = db.Videos.Where(e => e.PubYN == true)
                                 .Where(e => e.CatID == id)
                                 .OrderBy(string.Format("{0} {1}", order, orderDir))
                                 .ToPagedList(pageNumber - 1, pageSize);
            }

            videoModel.VideoImagePath = Settings.Default.SiteRootPath + Settings.Default.VideoImageRootPath;
            videoModel.VideoImageUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoImagePreviewUrlPrefix;

            videoModel.VideoFilePath = Settings.Default.SiteRootPath + Settings.Default.VideoRootPath;
            videoModel.VideoFileUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoPreviewUrlPrefix;
            
            return View(videoModel);
        }

        public ActionResult Details(int id)
        {
            VideoDetailViewModels v = new VideoDetailViewModels();
            v.Video = db.Videos.Where(e => e.ID == id).SingleOrDefault();
            if (v.Video != null)
            {
                v.VideoImagePath = Settings.Default.SiteRootPath + Settings.Default.VideoImageRootPath;
                v.VideoImageUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoImagePreviewUrlPrefix;

                v.VideoFilePath = Settings.Default.SiteRootPath + Settings.Default.VideoRootPath;
                v.VideoFileUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoPreviewUrlPrefix;

                v.Video.nViews = v.Video.nViews + 1;
                db.SubmitChanges();
            }
            return View(v);
        }
        [ChildActionOnly]
        public ActionResult OtherItems(int id, int number,string source, string title, int pubYN, string order, string orderDir)
        {
            var v = new VideoDetailViewModels();

            v.Video = db.Videos.Where(e => e.ID == id).SingleOrDefault();
            v.Videos = db.Videos
                .Where(e => pubYN > 0 ? e.PubYN == true : true)
                .Where(e => source != string.Empty ? e.Source == source : true)
                .Where(e => v.Video != null ? (v.Video.ID != e.ID && e.CatID == v.Video.CatID) : true)
                .OrderBy(string.Format("{0} {1}", order, orderDir)).Take(number).ToList();
            ViewData["Title"] = title;
            return View(v);
        }
        [ChildActionOnly]
        public ActionResult OtherItemsInInvestors(int id, int number, string title, int pubYN, string order, string orderDir)
        {
            var v = new VideoDetailViewModels();
            v.Video = db.Videos.Where(e => e.ID == id).SingleOrDefault();
            //Get project mapping video
            var p = v.Video.VideoProjectMaps.Where(e => e.VideoID==id).FirstOrDefault();
            // Get Investor
            var c = p != null ? p.Project.ProjectCompanyMaps.Where(e => e.TypeID == ProjectCompanyListType.Investors).FirstOrDefault() : null;
            if (c != null)
            {
                var l = (from m in c.Company.ProjectCompanyMaps
                         where m.TypeID == ProjectCompanyListType.Investors
                         select m.Project.ID).ToList();
                v.Videos = db.Videos
                    .Where(e => pubYN > 0 ? e.PubYN == true : true)
                    .Where(e => e.VideoProjectMaps.Where(k=>l.ToArray().Contains(k.ProjectID)==true).ToList().Count>0)
                    .Where(e => v.Video != null ? (v.Video.ID != e.ID && e.CatID == v.Video.CatID) : true)
                    .OrderBy(string.Format("{0} {1}", order, orderDir)).Take(number).ToList();
            }
            ViewData["Title"] = title;
            return View(v);
        }
        [ChildActionOnly]
        public ActionResult OtherItemsInCity(int id, int number, string title, int pubYN, string order, string orderDir)
        {
            var v = new VideoDetailViewModels();
            v.Video = db.Videos.Where(e => e.ID == id).SingleOrDefault();
            //Get project mapping video
            var p = v.Video.VideoProjectMaps.Where(e => e.VideoID == id).FirstOrDefault();
            if (p != null)
            {
                
                v.Videos = db.Videos
                    .Where(e => pubYN > 0 ? e.PubYN == true : true)
                    .Where(e => e.VideoProjectMaps.Where(k => k.Project.CityID==p.Project.CityID).ToList().Count > 0)
                    .Where(e => v.Video != null ? (v.Video.ID != e.ID && e.CatID == v.Video.CatID) : true)
                    .OrderBy(string.Format("{0} {1}", order, orderDir)).Take(number).ToList();
            }
            ViewData["Title"] = title;
            return View(v);
        }
        [ChildActionOnly]
        public ActionResult OtherItemsInProjectCategory(int id, int number, string title, int pubYN, string order, string orderDir)
        {
            var v = new VideoDetailViewModels();
            v.Video = db.Videos.Where(e => e.ID == id).SingleOrDefault();
            //Get project mapping video
            var p = v.Video.VideoProjectMaps.Where(e => e.VideoID == id).FirstOrDefault();
            if (p != null)
            {

                v.Videos = db.Videos
                    .Where(e => pubYN > 0 ? e.PubYN == true : true)
                    .Where(e => e.VideoProjectMaps.Where(k => k.Project.CatID == p.Project.CatID).ToList().Count > 0)
                    .Where(e => v.Video != null ? (v.Video.ID != e.ID && e.CatID == v.Video.CatID) : true)
                    .OrderBy(string.Format("{0} {1}", order, orderDir)).Take(number).ToList();
            }
            ViewData["Title"] = title;
            return View(v);
        }
        [ChildActionOnly]
        public ActionResult OtherItemsInCompanyType(int id, int number, string title, int pubYN, string order, string orderDir)
        {
            var v = new VideoDetailViewModels();
            v.Video = db.Videos.Where(e => e.ID == id).SingleOrDefault();
            //Get project mapping video
            var p = v.Video.VideoCompanyMaps.Where(e => e.VideoID == id).FirstOrDefault();
            if (p != null)
            {
                var type=p.Company.CompanyTypeMaps.FirstOrDefault();
                var typeid=type!=null? type.CompanyTypeID:0;
                v.Videos = db.Videos
                    .Where(e => pubYN > 0 ? e.PubYN == true : true)
                    .Where(e => e.VideoCompanyMaps.Where(k => k.Company.CompanyTypeMaps.Where(m=>m.CompanyTypeID == typeid).ToList().Count>0).ToList().Count > 0)
                    .OrderBy(string.Format("{0} {1}", order, orderDir)).Take(number).ToList();
            }
            ViewData["Title"] = title;
            return View(v);
        }
        [ChildActionOnly]
        public ActionResult OtherItemsInCompanyCity(int id, int number, string title, int pubYN, string order, string orderDir)
        {
            var v = new VideoDetailViewModels();
            v.Video = db.Videos.Where(e => e.ID == id).SingleOrDefault();
            //Get project mapping video
            var p = v.Video.VideoCompanyMaps.Where(e => e.VideoID == id).FirstOrDefault();
            if (p != null)
            {
                var type = p.Company.CompanyTypeMaps.FirstOrDefault();
                var typeid = type != null ? type.CompanyTypeID : 0;
                v.Videos = db.Videos
                    .Where(e => pubYN > 0 ? e.PubYN == true : true)
                    .Where(e => e.VideoCompanyMaps.Where(k => k.Company.CityID==p.Company.CityID.Value).ToList().Count > 0)
                    .OrderBy(string.Format("{0} {1}", order, orderDir)).Take(number).ToList();
            }
            ViewData["Title"] = title;
            return View(v);
        }
        [ChildActionOnly]
        public ActionResult Lasted(int catid, int number, string title)
        {
            var v = new VideoDetailViewModels();
            var listHome = db.Videos
                .Where(e => catid > 0 ? e.CatID == catid : true)
                .Where(e => e.HomeYN == true).OrderByDescending(e => e.ID).ToList();
            v.Video = listHome != null && listHome.Count > 0 ? listHome.First() : new Video();
            v.VideoImagePath = Settings.Default.SiteRootPath + Settings.Default.VideoImageRootPath;
            v.VideoImageUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoImagePreviewUrlPrefix;

            v.VideoFilePath = Settings.Default.SiteRootPath + Settings.Default.VideoRootPath;
            v.VideoFileUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoPreviewUrlPrefix;
            v.Videos = db.Videos.Where(e => e.PubYN == true)
                .Where(e => v.Video != null ? v.Video.ID != e.ID : true)
                .Where(e=>catid>0 ?e.CatID==catid:true)
                .OrderByDescending(e => e.ID).Take(number).ToList();
            if (listHome.Count>0)
            {
                v.Video = v.Videos.First();
            }
            ViewData["Title"] = title == string.Empty ? "Bất động sản TV" : title;
            return View(v);
        }
        [ChildActionOnly]
        public ActionResult Most(int catid, int number, string title, string order, string orderDir)
        {
            var v = new VideoDetailViewModels();
            var listHome = db.Videos
                .Where(e => catid > 0 ? e.CatID == catid : true)
                .Where(e => e.HomeYN == true).OrderBy(string.Format("{0} {1}", order, orderDir)).Take(number).ToList();
            v.Video = listHome != null && listHome.Count > 0 ? listHome.First() : null;
            v.VideoImagePath = Settings.Default.SiteRootPath + Settings.Default.VideoImageRootPath;
            v.VideoImageUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoImagePreviewUrlPrefix;

            v.VideoFilePath = Settings.Default.SiteRootPath + Settings.Default.VideoRootPath;
            v.VideoFileUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoPreviewUrlPrefix;
            v.Videos = db.Videos.Where(e => e.PubYN == true)
                .Where(e => v.Video != null ? v.Video.ID != e.ID : true)
                .Where(e => catid > 0 ? e.CatID == catid : true)
                .OrderBy(string.Format("{0} {1}", order, orderDir)).Take(number).ToList();
            if (v.Video == null && v.Videos.Count > 0)
            {
                v.Video = v.Videos.First();
            }
            ViewData["Title"] = title == string.Empty ? "Bất động sản TV" : title;
            return View(v);
        }
        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 09/08/2011
        /// </summary>
        [ChildActionOnly]
        public ActionResult GetTop(int number, int skip, string order, string orderDir)
        {
            VideoIndexViewModels model = new VideoIndexViewModels();

            model.Videos = db.Videos.Where(e => e.PubYN == true)
                             .OrderBy(string.Format("{0} {1}", order, orderDir))
                             .Skip(skip).Take(number).ToList();
            model.VideoImagePath = Settings.Default.SiteRootPath + Settings.Default.VideoImageRootPath;
            model.VideoImageUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoImagePreviewUrlPrefix;

            model.VideoFilePath = Settings.Default.SiteRootPath + Settings.Default.VideoRootPath;
            model.VideoFileUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoPreviewUrlPrefix;

            return View(model);
        }

        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 08/08/2011
        /// </summary>
        [ChildActionOnly]
        public ActionResult GetByCat(int number, int skip, int catid, string title, string order, string orderDir)
        {
            VideoIndexViewModels model = new VideoIndexViewModels();

            model.Category = db.VideoCategories.Where(vc => vc.ID == catid && vc.ActiveYN == true).FirstOrDefault();
            ViewData["title"] = title;
            model.Videos = db.Videos.Where(e => e.PubYN == true)
                             .Where(e => e.CatID == catid)
                             .OrderBy(string.Format("{0} {1}", order, orderDir))
                             .Skip(skip).Take(number).ToList();
            model.VideoImagePath = Settings.Default.SiteRootPath + Settings.Default.VideoImageRootPath;
            model.VideoImageUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoImagePreviewUrlPrefix;

            model.VideoFilePath = Settings.Default.SiteRootPath + Settings.Default.VideoRootPath;
            model.VideoFileUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoPreviewUrlPrefix;

            return View(model);
        }
        [ChildActionOnly]
        public ActionResult LatestComments(int id, int number)
        {
            var latestC = new List<Comment>();
            try
            {
                latestC = VideoManager.GetComments(id, true, number).ToList();
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
            }
            return PartialView(latestC);
        }
        [ChildActionOnly]
        public ActionResult Comment(int id)
        {
            CommentEditModels c = new CommentEditModels();
            c.ObjectID = id;
            var u = Membership.GetUser();
            if (u != null)
            {
                c.FullName = u.UserName;
                c.Email = u.Email;
            }
            return PartialView(c);
        }       
               

        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 11/08/2011
        /// </summary>
        [ChildActionOnly]
        public ActionResult TagLasted(int id, string title)
        {
            ViewData["title"] = title;
            List<Tag> lTag = db.VideoTagMaps.Where(vt => vt.VideoID == id)
                                            .OrderBy("Tag.Keyword desc")
                                            .Select(vt => vt.Tag)
                                            .ToList();
            
            return View(lTag);
        }

        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 11/08/2011
        /// </summary>
        public ActionResult Tag(int id, int? page)
        {
            page = page.HasValue && page.Value > 0 ? page.Value : 1;
            VideoListViewModel videoModel = new VideoListViewModel();
            ViewData["Keyword"] = db.Tags.Where(t => t.ID == id).FirstOrDefault().Keyword;
            string order = UserState.getUserStateFromRequest("videoCategory.order", "order", "Video.AddDate").ToString();
            string orderDir = UserState.getUserStateFromRequest("videoCategory.orderDir", "orderDir", "desc").ToString();
            int pageNumber = Convert.ToInt32(UserState.getUserStateFromRequest("videoCategory.PageNumber", "page", 1));
            int pageSize = int.Parse(UserState.getUserStateFromRequest("videoCategory.pageSize", "PageSize", 20).ToString());

            videoModel.VideoImageUrl = Settings.Default.AdminRootUrl + Settings.Default.VideoRootUrl;
            videoModel.Category = db.VideoCategories.Where(vc => vc.ActiveYN == true && vc.ID == id).FirstOrDefault();
            videoModel.Videos = db.VideoTagMaps.Where(vt => vt.TagID == id)
                             .Where(vt => vt.Video.PubYN == true)
                             .OrderBy(string.Format("{0} {1}", order, orderDir))
                             .Select(vt=>vt.Video)
                             .ToPagedList(page.Value - 1, pageSize);

            videoModel.VideoImagePath = Settings.Default.SiteRootPath + Settings.Default.VideoImageRootPath;
            videoModel.VideoImageUrl = Settings.Default.AdminRootUrl + Settings.Default.VideoImagePreviewUrlPrefix;

            videoModel.VideoFilePath = Settings.Default.SiteRootPath + Settings.Default.VideoRootPath;
            videoModel.VideoFileUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoPreviewUrlPrefix;

            return View(videoModel);
        }
    }
}
